package com.shuhe.common;

import com.alibaba.fastjson.JSONObject;
import com.shuhe.domain.mxgc.CommonResponseBody;
import com.shuhe.domain.mxgc.DynamicBean;
import com.shuhe.domain.mxgc.SqlRequestBody;
import com.shuhe.domain.mxgc.SqlResponseBody;
import com.shuhe.metastore.DBSql;
import com.shuhe.metastore.MetaMysql;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.apache.log4j.Logger;
import org.influxdb.InfluxDB;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonFunction {

    private static Logger logger = Logger.getLogger(CommonFunction.class);

    public static void closeDb(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
                logger.error(ex.getMessage());
                ex.printStackTrace();
            }
        }
    }

    public static void closeDbInflux(InfluxDB conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
                logger.error(ex.getMessage());
                ex.printStackTrace();
            }
        }
    }

    public static HttpServletResponse setResponse(HttpServletResponse resp) {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setContentType("application/json;charset=UTF-8");
        return resp;
    }

    public static String readAsChars(HttpServletRequest request) throws Exception {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    //查询用户对应角色
    public static String getRoleStr(String userName, Connection metaConn) throws Exception {
        String sql =
                "select role_id from sys_role where role_id in " + "(select role_id from sys_user_role where " +
                        "user_id in " + "(select user_id from sys_user where login_name = '" + userName + "'))";
        ResultSet rs = MetaMysql.querySql(metaConn, sql);
        String roleStr = "";
        while (rs.next()) {
            roleStr = roleStr + "'" + rs.getString("role_id") + "',";
        }
        if (roleStr.length() > 0) {
            roleStr = roleStr.substring(0, roleStr.length() - 1);
        }
        return roleStr;
    }

    public static String returnFail(String reason) {
        SqlResponseBody sqlResp = new SqlResponseBody();
        CommonResponseBody comm = new CommonResponseBody();
        comm.setFail(reason);
        sqlResp.setCommon(comm);
        String respJson = JSONObject.toJSONString(sqlResp);
        return respJson;
    }

    public static String resultSuccess(CommonResponseBody comm) {
        SqlResponseBody body = new SqlResponseBody();
        body.setCommon(comm);
        String respJson = JSONObject.toJSONString(body);
        return respJson;

    }

    public static JSONObject getResultJson(String status, String message){
        JSONObject result = new JSONObject();
        JSONObject common = new JSONObject();
        common.put("status", status);
        common.put("msg", message);
        result.put("common", common);
        return result;
    }

    public static ArrayList<Object> getResultSet(ResultSet rs) throws Exception {
        ArrayList<Object> datas = new ArrayList();
        DynamicBean dynamicBean = new DynamicBean();
        while (rs.next()) {
            ResultSetMetaData rsd = rs.getMetaData();
            Map<String, Object> addProperties = new HashMap();
            for (int i = 1; i <= rsd.getColumnCount(); i++) {
                Object fieldValue = rs.getObject(i);

                if (fieldValue == null) {
                    fieldValue = "";
                }
                if (fieldValue.getClass().getName().indexOf("Array") >= 0 ||
                                fieldValue.getClass().getName().indexOf("object") >= 0 ||
                                fieldValue.getClass().getName().indexOf("Boolean") >= 0 ||
                                fieldValue.getClass().getName().indexOf("Time") >= 0 ||
                        fieldValue.getClass().getName().indexOf("Date") >= 0 )
                 {
                    fieldValue = rs.getString(i);
                }


                String fieldStr = rsd.getColumnLabel(i);
                fieldStr = fieldStr.toLowerCase();
                addProperties.put(fieldStr, fieldValue);
                if (fieldStr.equals("value")) {
                    addProperties.put("key", fieldValue);
                }
            }
            Object obj = ReflectUtil.getTarget(dynamicBean, addProperties);
            datas.add(obj);
        }
        return datas;
    }

    public static CommonResponseBody getCommonResponseBody(long beginTime) {
        long endTime = Calendar.getInstance().getTimeInMillis();
        String qTime = String.valueOf(endTime - beginTime);
        CommonResponseBody comm = new CommonResponseBody();
        comm.setSuccess();
        comm.setQtime(qTime);
        return comm;
    }

    public static boolean ifChinese(String source) {
        String reg_charset = "[\\u4E00-\\u9FFF]+";
        Pattern p = Pattern.compile(reg_charset);
        Matcher m = p.matcher(source);
        return m.find();
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getPingYin(String inputString) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String output = "";
        if (null != inputString && 0 < inputString.length() && !"null".equals(inputString)) {
            char[] input = inputString.trim().toCharArray();
            try {
                for (int i = 0; i < input.length; i++) {
                    if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
                        output += temp[0];
                    } else {
                        output += Character.toString(input[i]);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "";
        }
        return output;
    }

    public static String getFirstPingYin(String chines) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    public static String dealNull(String value, String defaultVal) {
        if (value == null) {
            value = defaultVal;
        }
        return value;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getPingYin("中华人民共和国wyx一起来"));
        System.out.println(getFirstPingYin("中华人民共和国wyx一起来"));
    }

}
